import { defineStore } from 'pinia'
import { getApiList } from '../server'
import type { RootObject, Cities, StatisGradeCityDetail, cofirmRank } from './type'

export const useStore = defineStore({
  id: 'counter',
  state: () => ({
    list: <RootObject>{},
    item: <Cities[]>[],
    cityDetail: <StatisGradeCityDetail[]>[],
    cofirmRank: <cofirmRank[]>[],
  }),
  getters: {
    // 累计确诊人数
    totalConfirmed: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.confirmed, 0);
    },
    // 现有确诊人数
    currentConfirmed: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.current_confirmed, 0);
    },
    // 无症状感染者
    asympTomatic: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.asymptomatic, 0);
    },
    // 新增确诊人数
    newConfirmed: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.new_confirmed, 0);
    },
    // 新增治愈人数
    newRecovered: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.new_recovered, 0);
    },
    // 累计死亡人数
    newDeaths: (state) => {
      return Object.values(state.item).reduce((sum, item) => sum + item.new_deaths, 0);
    }
  },
  actions: {
    async getList() {
      const result = await getApiList()
      this.list = result
      console.log(this.list.data)

      // 1. 提取所有城市数据
      const allCities = this.list.data.flatMap(province => province.cities);
      // 2. 按 current_confirmed 从大到小排序
      const sortedCities = allCities.sort((a, b) => b.current_confirmed - a.current_confirmed);
      // 3. 截取前 10 个城市
      const top10Cities = sortedCities.slice(0, 10);
      // 4. 提取 city 和 current_confirmed
      this.cityDetail = top10Cities.map(c => ({
        city: c.city,
        current_confirmed: c.current_confirmed
      }));


      //确诊人数省份排行

      // 1. 计算每个省份的 confirmed 总和
      const provinceData = this.list.data.map(province => {
        const totalConfirmed = province.cities.reduce((sum, city) => sum + Number(city.confirmed), 0);
        return {
          p: province.province,
          totalConfirmed: totalConfirmed
        };
      });

      // 2. 按 totalConfirmed 从大到小排序
      const sortedProvinces = provinceData.sort((a, b) => b.totalConfirmed - a.totalConfirmed);

      // 3. 截取前 10 个省份
      const top10Provinces = sortedProvinces.slice(0, 10);

      // 4. 输出结果
      this.cofirmRank = top10Provinces.map(province => ({
        province: province.p,
        total_confirmed: province.totalConfirmed
      }));

      console.log(this.cofirmRank);
    }
  }
})
